#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <iostream>
#include <fstream>
#include <cstring>
#include <filesystem>

namespace fs = std::filesystem;

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cerr << "Usage: " << argv[0] << " <output_directory>" << std::endl;
        return 1;
    }

    const char *output_directory = argv[1];

    // 检查输出目录是否存在
    if (!fs::exists(output_directory))
    {
        std::cerr << "Output directory does not exist: " << output_directory << std::endl;
        return 1;
    }

    using namespace boost::interprocess;

    // 打开共享内存对象
    shared_memory_object shm(open_only, "FileSharedMemory", read_only);

    // 映射共享内存到当前进程的地址空间
    mapped_region region(shm, read_only);

    // 获取指向共享内存的指针
    void *addr = region.get_address();

    // 从共享内存读取文件名
    char file_name[256];
    std::strcpy(file_name, static_cast<char *>(addr));

    // 提取文件名（不包括路径）
    const char *base_name = std::strrchr(file_name, '/');
    if (!base_name)
    {
        base_name = file_name;
    }
    else
    {
        ++base_name; // 跳过 '/'
    }

    // 从共享内存读取文件内容
    char *file_content = static_cast<char *>(addr) + 256;
    std::streamsize size = region.get_size() - 256;

    // 在指定目录下生成同名文件
    fs::path output_path = fs::path(output_directory) / base_name;
    std::ofstream output_file(output_path, std::ios::binary);
    if (!output_file)
    {
        std::cerr << "Error creating file: " << output_path << std::endl;
        return 1;
    }

    output_file.write(file_content, size);
    std::cout << "File content read from shared memory and written to: " << output_path << std::endl;

    // 读取完后删除共享内存对象
    shared_memory_object::remove("FileSharedMemory");

    return 0;
}
